<script setup>
import axios from 'axios';
import md5 from 'md5';

const getClientToken = async () => {
  const { data } = await axios.post('/oauth/client_token/', {
    client_key:"awuqn0hrlxer5q5c",
    client_secret:"b22a08bd767d831d6b300c768bda1967",
    grant_type: 'client_credential',
  });
  const { access_token } = data.data || {};
  return access_token;
};

const getTicket = async (access_token) => {
  const { data } = await axios.get('/js/getticket', {
    params: {
      access_token,
    },
  });
  const { ticket } = data.data || {};
  return ticket;
};
const calcSignature = ({ ticket, nonce_str, timestamp, url }) => {
  const str = `jsapi_ticket=${ticket}&nonce_str=${nonce_str}&timestamp=${timestamp}&url=${url}`;
  const sig = md5(str);
  return sig;
};


const tiktokShouQuan =  async () => {
  const sdk = window.douyin_open;
  const timestamp = String(parseInt(Date.now() / 1000)); // 类型为 String
  const nonceStr = Math.random(); // 生成签名用的随机字符串
  const url = location.href;
  // const access_token = await getClientToken();
  // const ticket = await getTicket({ access_token });
  const ticket="#kOomyjZtek8vAcFfKZe5FaAJ/7VHZT16ej4mlfleg8Ot1oMqIwbhCcPgAZbnpKLEKbQ0rXzAaBtFMm7XfFBjNA==";
  
  sdk.config({
    params: {
      client_key: "awuqn0hrlxer5q5c", // clientKey在你的网页应用申请通过后得到
      signature: calcSignature(ticket,nonceStr,timestamp, url), // 服务端计算的签名，该签名被抖音开放平台验证通过后方可调用jsb方法
      timestamp, // 时间戳
      nonce_str: nonceStr,
      url, // 为应用申请的 JSB 安全域名下的链接，需要携带协议。e.g. https://jsb.security.domain/page.html
    },
  });
  sdk.ready(() => {
    alert("成功了")
  })
  sdk.error((res) => {
    // Config error回调
    alert("失败了，"+JSON.stringify(res));
  });
}



</script>

<template>
  <div>
    <div style="height: 100px;" ></div>
    <div style="width: 100%;text-align: center;" ><button @click="tiktokShouQuan" >授权</button></div>
  </div>
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
